package com.lagou.rpc.consumer.proxy;

import com.alibaba.fastjson.JSON;
import com.lagou.rpc.common.RpcRequest;
import com.lagou.rpc.common.RpcResponse;
import com.lagou.rpc.consumer.client.RpcClient;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 客户端代理类-创建代理对象
 * 1。封装request对象
 * 2。创建RpcClient对象
 * 3。发送消息
 * 4。返回结果
 */
public class RpcClientProxy {

    private static Map<Integer, String> serverMap = new HashMap<>();
    private static int serverIndex;
    private static int requestCount;
    //上次请求的服务器索引
    static {
        serverMap.put(0, "127.0.0.1:8899");
        serverMap.put(1, "127.0.0.1:8898");
    }

    private static String getServer(){
        serverIndex = (requestCount++) % serverMap.size();
        String server = serverMap.get(serverIndex);
        return server;
    }

    public static Object createProxy(Class serviceClass){
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                new Class[]{serviceClass}, new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        //1。封装request对象
                        RpcRequest rpcRequest = new RpcRequest();
                        rpcRequest.setRequestId(UUID.randomUUID().toString());
                        rpcRequest.setClassName(method.getDeclaringClass().getName());
                        rpcRequest.setParameterTypes(method.getParameterTypes());
                        rpcRequest.setParameters(args);
                        rpcRequest.setMethodName(method.getName());
                        //2。创建RpcClient对象
                        String server = getServer();
                        String[] strings = server.split(":");
                        RpcClient rpcClient = new RpcClient(strings[0], Integer.parseInt(strings[1]));
                        System.out.println("-------rpcClient：" + server + "创建成功-----");
                        try {
                            //3。发送消息
                            Object responseMsg = rpcClient.send(JSON.toJSONString(rpcRequest));
                            RpcResponse rpcResponse = JSON.parseObject(responseMsg.toString(), RpcResponse.class);
                            if (rpcResponse.getError() != null){
                                throw new RuntimeException(rpcResponse.getError());
                            }
                            //4。返回结果
                            Object result = rpcResponse.getResult();
                            return JSON.parseObject(result.toString(), method.getReturnType());
                        } catch (Exception e){
                            throw e;
                        } finally {
                            rpcClient.close();
                        }
                    }
                });
    }

}
